package com.lvjunxiong.serviceinterface;


import com.lvjunxiong.serviceinterface.tongxun.R;
import net.sf.json.JSONObject;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * demo链接：
 * https://blog.csdn.net/lhc_makefunny/article/details/81171194
 */
public class Serviceutil {
    private static Logger logger = Logger.getLogger(Serviceutil.class);
    //获取code接口
    public static String getCode(String client_id, String response_type, String redirect_uri,String username,String userpass) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String url = "http://app.shuhai.cc/isms/oauth/authorize?client_id=" + client_id + "&"
                + "response_type=" + response_type + "&" + "userName=" + ""+ username +"" + "&" + "password=" + ""+ userpass +"" + "&" + "redirect_uri=" + redirect_uri;

        HttpGet httpGet = new HttpGet(url);
        RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).setConnectionRequestTimeout(5000)
                .build();
        httpGet.setConfig(config);

        String result = "";
        try {
            HttpResponse response = httpClient.execute(httpGet);
            Header url1 = response.getFirstHeader("Location");
            // 从从定向地址中取得code
            if (response.getStatusLine().getStatusCode() == 302) {
                Header header = response.getFirstHeader("Location");
                String location = header.getValue();
                String code = location.substring(location.indexOf("=") + 1, location.length());
                return code;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            e.printStackTrace();
        }
        return "error";
    }

    public static String getCodetest(String client_id, String response_type, String redirect_uri, String username, String userpass) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String url = "http://app.shuhai.cc/isms/oauth/authorize?client_id=" + client_id + "&"
                + "response_type=" + response_type + "&" + "userName=" + "" + username + "" + "&" + "password=" + "" + userpass + "" + "&" + "redirect_uri=" + redirect_uri;

        HttpGet httpGet = new HttpGet(url);
        RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).setConnectionRequestTimeout(5000)
                .build();
        httpGet.setConfig(config);

        String result = "";
        try {
            HttpResponse response = httpClient.execute(httpGet);
            Header url1 = response.getFirstHeader("Location");
            // 从从定向地址中取得code
            if (response.getStatusLine().getStatusCode() == 302) {
                Header header = response.getFirstHeader("Location");
                String location = header.getValue();
                String code = location.substring(location.indexOf("=") + 1, location.length());
                return code;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            e.printStackTrace();
        }
        return "error";
    }

    //获取token接口
    public static String doPost(String url, Map<String, Object> paramMap) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 创建httpClient实例
        httpClient = HttpClients.createDefault();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(url);
        // 配置请求参数实例
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(60000)// 设置连接请求超时时间
                .setSocketTimeout(60000)// 设置读取数据连接超时时间
                .build();
        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);
        // 设置请求头
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // 封装post请求参数
        if (null != paramMap && paramMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 通过map集成entrySet方法获取entity
            Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
            // 循环遍历，获取迭代器
            Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = iterator.next();
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }

            // 为httpPost设置封装好的请求参数
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            // httpClient对象执行post请求,并返回响应参数对象
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    //获取团体id接口
    public static String doPost(String url, String params) throws Exception {

    	System.err.println("url>>>>>>>>>>>>>>>>>>>"+url+"????????"+params);
    	
    	
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            System.out.println(state + "=====>>>>>>>>>>>>>>>");
            System.out.println("state>>.."+state+"           HttpStatus.SC_OK"+HttpStatus.SC_OK);
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                System.out.println("jsonString>>>>>>>>>"+jsonString);
                return jsonString;
            } else {
                logger.error("请求返回:" + state + "(" + url + ")");
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static Map<String, Object> sendGet(String sendUrl) {
        Map<String, Object> mres = new HashMap<String, Object>();
        // 默认配置创建一个httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建httpGet远程连接实例
        HttpGet httpGet = new HttpGet(sendUrl);
        // 设置配置请求参数
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(35000)// 连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 请求超时时间
                .setSocketTimeout(60000)// 数据读取超时时间
                .build();
        // 为httpGet实例设置配置
        httpGet.setConfig(requestConfig);
        try {
            // 执行get请求得到返回对象
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            String result = EntityUtils.toString(entity, "UTF-8");
            mres = (Map<String, Object>) JSONObject.toBean(JSONObject.fromObject(result), Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return mres;
    }


    /**
     * 设置请求参数
     *
     * @param
     * @return
     */
    private static List<NameValuePair> setHttpParams(Map<String, String> paramMap) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        Set<Map.Entry<String, String>> set = paramMap.entrySet();
        for (Map.Entry<String, String> entry : set) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return formparams;
    }

    /**
     * 获得响应HTTP实体内容
     *
     * @param response
     * @return
     * @throws java.io.IOException
     * @throws java.io.UnsupportedEncodingException
     */
    private static String getHttpEntityContent(HttpResponse response) throws IOException, UnsupportedEncodingException {
        //通过HttpResponse 的getEntity()方法获取返回信息
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream is = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = br.readLine();
            StringBuilder sb = new StringBuilder();
            while (line != null) {
                sb.append(line + "\n");
                line = br.readLine();
            }
            br.close();
            is.close();
            return sb.toString();
        }
        return "";
    }

    public static String postPayMsg(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException {
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
        httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> formparams = setHttpParams(paramMap);
        UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, "UTF-8");
        //通过setEntity()设置参数给post
        httpPost.setEntity(param);
        //利用httpClient的execute()方法发送请求并且获取返回参数
        HttpResponse response = httpClient.execute(httpPost);
        String httpEntityContent = getHttpEntityContent(response);
        httpPost.abort();
        return httpEntityContent;
    }

    /**
     * 清理特殊字符以便得到
     *
     * @param chines
     * @return
     */
    public static String cleanChar(String chines) {
        chines = chines.replaceAll("[\\p{Punct}\\p{Space}]+", ""); // 正则去掉所有字符操作
        // 正则表达式去掉所有中文的特殊符号
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}<>《》【】‘；：”“’。，、？]";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(chines);
        chines = matcher.replaceAll("").trim();
        return chines;
    }


    public static String converterToFirstSpell(String chines) {
        chines = cleanChar(chines);
        String pinyinName = "";
        char[] nameChar = chines.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < nameChar.length; i++) {
            if (nameChar[i] > 128) {
                try {
                    pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0].charAt(0);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinName += nameChar[i];
            }
        }
        return pinyinName;

    }

    public static void main(String[] args) throws Exception {
//        String s = getCode("466b9b72b2db227647e5a70d3bde6dc0","code","http://app.shuhai.cc/isms/index");
//        System.out.println(s + "====123");
///*        AccessToken ff = getToken("466b9b72b2db227647e5a70d3bde6dc0", "authorization_code", s, "http://app.shuhai.cc/isms/index",
//                "00cfc1826358a21a4bfadec2324ceba9");
//        System.out.println(ff.getAccess_token() + "=======123456");*/
//        Map<String, Object> paramMap = new HashMap<String, Object>();
//        paramMap.put("client_id","466b9b72b2db227647e5a70d3bde6dc0");
//        paramMap.put("grant_type","authorization_code");
//        paramMap.put("code",s);
//        paramMap.put("redirect_uri", "http://app.shuhai.cc/isms/index");
//        paramMap.put("client_secret","00cfc1826358a21a4bfadec2324ceba9");
//        String ssss = doPost("http://app.shuhai.cc/isms/oauth/accessToken", paramMap);
//        System.out.println(ssss  + "====78797897");
          //工资接口(通)--没有数据，需要核对信息
//          String gongzijiekou = doPost("http://app.shuhai.cc/isms/manager/employeewages/query/40280a816859f2c1016859fb72c20033", "");
//          System.out.println(gongzijiekou);
//        StringBuilder builder = new StringBuilder();
//        builder.append("http://app.shuhai.cc/isms/manager/party/all/");
//        builder.append("1a7d9182c53299599df1ff277c60bf79");
//        Map<String, Object> resultGet = sendGet(builder.toString());
//        System.out.println(resultGet);
          //获得团体通讯录接口-没有数据,需要核对信息
//          builder.append("http://app.shuhai.cc/isms/manager/party/all/");
//          builder.append("1a7d9182c53299599df1ff277c60bf79");
//          Map<String, Object> resultGet = sendGet(builder.toString());
//          System.out.println(resultGet);


        /*String result = doPost("http://app.shuhai.cc/isms/manager/employeewages/query/40280a816859f2c1016859fb72c20033", "2019年1月");
        System.out.println(result);
        JSONObject jo_ = JSONObject.fromObject(result);
        JSONArray rows = jo_.getJSONArray("rows");
        for (int i = 0; i < rows.size(); i++) {
            String res = rows.getString(i);
            JsonParser jps = new JsonParser();
            JsonObject jos = jps.parse(res).getAsJsonObject();
            String gain_months = jos.get("months").getAsString();//日期
            String gain_Name = jos.get("name").getAsString();//姓名
//            System.out.println(gain_months + "==获取到的日期和姓名==" + gain_Name);
            //获取lists集合中的项目名称和金额
            JsonArray lists = jos.get("lists").getAsJsonArray();
            for (int j = 0; j < lists.size(); j++) {
                JsonElement list_ = lists.get(j);
                JsonArray gain_lists = lists.get(j).getAsJsonArray();

                if(gain_lists.size() >0){
                    JsonElement one = gain_lists.get(0);
                    JsonElement two = gain_lists.get(1);
//                    System.out.println(one.toString() + "==end==" + two.toString());
                    HashMap<String,String> map = new HashMap<String, String>();
                    map.put(two.toString(), one.toString());
                    boolean contains = map.containsKey("".toString());
                    //如果包含""不获取，否则获取
                    System.out.println(contains + "=====");
                    if (contains) {
                    } else {
                        for(String key:map.keySet()){//keySet获取map集合key的集合  然后在遍历key即可
                             String value = map.get(key).toString();//
                             System.out.println("key:" + key + " vlaue:" + value);
                        }
                    }
                }
            }
        }*/
//        String time = "2018-01";
//        String year = time.substring(0, 4);
//        String month = time.substring(5, 7);
//        System.out.println("年："+year);
//        System.out.println("月："+ Integer.parseInt(month));
//        String result = doPost("http://app.shuhai.cc/shcmweb/service/phoneVerification/ValidateYZM?id=b8af9a5464c14546ad73b95d9abca33f&dxyzm=973467&phone=18003461927", "");
//        System.out.println(result + "======");
        //String ff = doPost("http://app.shuhai.cc/isms/manager/party/getCorporation/374b8c0569c388510169c39eb9b700f4", "");

        //白伟平的父级id
        //String ffdddd = doPost("http://app.shuhai.cc/isms/manager/party/getParent/374b8c0569c388510169c39e333d00e6", "");
        //System.out.println(ffdddd);

//        String ffdddd = doPost("http://app.shuhai.cc/isms/manager/party/contact/4028f69f55304e0b01553279b6310042", "");
//        System.out.println(ffdddd);

//        String  all_tongxunlist = doPost("http://app.shuhai.cc/isms/manager/party/all/4028f69f55304e0b01553279b6310042", "");
//        System.out.println(all_tongxunlist + "=====123");


//        String dd = doPost("http://app.shuhai.cc/isms/manager/party/contact/374b8c0569c388510169c39eb9b700f4", "");
//        System.out.println(dd + "=======");


        String ff = converterToFirstSpell("吕");


        System.out.println(ff);
    }
}